@SpringBootTest
class PayItemMapperTest {

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private AlipayCommonConfig alipayCommonConfig;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void payMapperTest() throws UnsupportedEncodingException, AlipayApiException {
        List<Integer> songIds = new ArrayList<>();
        songIds.add(1);
        List<Song> songs = songMapper.selectBatchIds(songIds);

        //组装支付清单和清单子项并求清单的总金额
        //产生清单编号
        String payNo = RandomCodeGenerate.createOrderNo();
        List<PayItem> payItems = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.valueOf(0.0);
        for (Song s: songs) {
            PayItem item = new PayItem();
            item.setPrice(s.getPrice());
            item.setSongId(s.getId());
            item.setTradeNo(payNo);
            item.setUserId(77);
            payItems.add(item);
            BigDecimal songPrice = BigDecimal.valueOf(item.getPrice());
            totalAmount = totalAmount.add(songPrice);
        }

        //组装订单
        Pay pay = new Pay();
        pay.setPayStatus(Constants.PAY_STATUS_1);
        pay.setPayType(1);
        pay.setSubject("歌曲下载");
        pay.setAmount(totalAmount.doubleValue());
        pay.setTradeNo(payNo);
        pay.setUserId(77);
        pay.setPayItems(payItems);

        //付款清单和清单子项暂存，待支付成功后核销
        redisTemplate.opsForValue().set(Constants.ALIPAY_REDIS_KEY + pay.getTradeNo().trim(),
                JSONObject.toJSONString(pay));

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayCommonConfig.getGateway_url(),
                alipayCommonConfig.getApp_id(),
                alipayCommonConfig.getApp_private_key(),
                alipayCommonConfig.getFormat(),alipayCommonConfig.getCharset(),
                alipayCommonConfig.getAlipay_public_key(),
                alipayCommonConfig.getSign_type());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //同步回调
        alipayRequest.setReturnUrl(alipayCommonConfig.getReturn_url());
        //支付宝支付成功服务器异步回调核销
        alipayRequest.setNotifyUrl(alipayCommonConfig.getNotify_url());

        Map<String,Object> bizContent = new HashMap<>();
        //订单号
        bizContent.put("out_trade_no",pay.getTradeNo());
        //销售产品码，与支付宝签约的产品码名称。目前仅支付FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
        //订单金额
        bizContent.put("total_amount",pay.getAmount());
        //中文乱码处理
        bizContent.put("subject",new String(pay.getSubject().getBytes("UTF-8"), "UTF-8"));
        alipayRequest.setBizContent(JSONObject.toJSONString(bizContent));
        String alipayResult = alipayClient.pageExecute(alipayRequest).getBody();

        System.out.println("支付mapper测试结果：" + alipayResult);
    }

}
